package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.DTO.DishDto;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.ICategoryService;
import com.itheima.service.IDishFlavorService;
import com.itheima.service.IDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    IDishService dishService;

    @Autowired
    IDishFlavorService dishFlavorService;

    @Autowired
    ICategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    //添加菜品
    @PostMapping
    private R addDish(@RequestBody DishDto dishDto){

        dishService.saveDishWithFlavor(dishDto);

        //保持数据的同步，删除reids中的数据
        redisTemplate.delete("redis_"+dishDto.getCategoryId());

        return R.success("添加菜品成功");
    }

    //分页查询菜品数据
    @GetMapping("/page")
    private R pageDish(Long page, Long pageSize,String name){

        IPage<Dish> Ipage = new Page<>(page,pageSize);
        //创建一个DishDTO对象，用来copy
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        IPage<Dish> page1 = dishService.page(Ipage);

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null&& !name.equals(""), Dish::getName,name)
                .orderByDesc(Dish::getCreateTime);

        dishService.page(page1,wrapper);

        //拷贝对象
        BeanUtils.copyProperties(Ipage,dishDtoPage,"records");

        List<Dish> records = Ipage.getRecords();
        //拷贝数据
        List<DishDto> dishDtoList = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            //查询是否有分类
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                //说明有分类
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    //回显菜单数据
    @GetMapping("/{id}")
    private R EchoDish(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    //修改菜品
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto){

        dishService.updateDishWithFlavor(dishDto);

        //保持数据的同步，删除全部reids中的数据
        Set keys = redisTemplate.keys("redis*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    //删除和批量删除
    @DeleteMapping
    private R deleteDish(Long[] ids){
        dishService.deleteDishById(ids);
        return R.success("删除成功");
    }

    //起售/停售 批量起售/批量停售
    @PostMapping("/{status}/{id}")
    private R updateStatus(@PathVariable Integer id, Long[] ids){
        dishService.updateStatus(id,ids);
        return R.success("修改成功");
    }

    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    private R<List<DishDto>> selectAll(Dish dish){
        //1.先在Redis中获取缓存
        String redisKey = "redis_"+dish.getCategoryId();
        Object o = redisTemplate.opsForValue().get(redisKey);

        //2.判断redis中是否为空
        if (o != null){
            //直接返回redis中数据
            return R.success((List<DishDto>) o);
        }

        ArrayList<DishDto> dishDtos = new ArrayList<>();

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        wrapper.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(wrapper);

        for (Dish d : list) {
            DishDto dishDto = new DishDto();
            //复制给dishDto
            BeanUtils.copyProperties(d,dishDto);

            //查看是否有口味
            LambdaQueryWrapper<DishFlavor> flavorWrapper = new LambdaQueryWrapper<>();
            flavorWrapper.eq(DishFlavor::getDishId,d.getId());

            List<DishFlavor> dishFlavors = dishFlavorService.list(flavorWrapper);

            dishDto.setFlavors(dishFlavors);
            dishDtos.add(dishDto);
        }

        //3.放到redis中
        redisTemplate.opsForValue().set(redisKey,dishDtos);
        return R.success(dishDtos);
    }

}
